from whiff.middleware import misc
from whiff import resolver
from whiff import whiffenv
from whiff.middleware import setInnerHtml

basicTypes = ["number", "string", "date", "currency"]

class clickCallBack(misc.utility):
    def __call__(self, env, start_response):
        env = resolver.process_cgi(env, parse_cgi=True)
        dataString = whiffenv.cgiGet(env, "data", "{}").strip()
        target = whiffenv.cgiGet(env, "target").strip()
        command = whiffenv.cgiGet(env, "command").strip()
        dataString = resolver.unquote(dataString)
        schemaData = self.param_json(dataString, env)
        if command:
            nameDisplay = 'Change <code>%s</code> <a href="#" onclick="deleteSet()">X</a>' % command
            name = command
            assert name in schemaData, "command should name existing description set: "+repr((name,schemaData))
            attributeList = schemaData[name]
        else:
            nameDisplay = "Add new description set"
            name = ""
            attributeList = []
        allnames = schemaData.keys()
        allnames.sort()
        availableKinds = allnames + basicTypes
        availableKinds = map(str, availableKinds)
        L = []
        jsL = []
        a = L.append
        b = jsL.append
        for attrDescr in attributeList:
            (attrInputs, attrJs) = self.attributeInputs(attrDescr, name)
            a(attrInputs)
            b(attrJs)
        (newInput,newJs) = self.attributeInputs({}, name)
        a(newInput)
        b(newJs)
        body = "\n".join(L)
        D = {}
        D["name"] = name
        D["nameDisplay"] = nameDisplay
        D["body"] = body
        D["availableKinds"] = availableKinds
        innerHtml = TEMPLATE % D
        jsPrefix = JSTEMPLATE % D
        #innerHtml = command+"\n"+dataString
        #pr "INNERHTML"
        #pr innerHtml
        #pr "ROW JAVASCRIPT"
        #for x in jsL:
            #pr x
        application = setInnerHtml.__middleware__(page=innerHtml, elementName=target)
        setHtml = self.param_value(application, env)
        #return self.deliver_page(application, env, start_response)
        start_response("200 OK", [('Content-Type', 'application/javascript')])
        return [setHtml, jsPrefix] + jsL
    def attributeInputs(self, attrDescr, setName): #name="", typeName="str", isIdentifier=False):
        name = attrDescr.get("name", "")
        typeName = attrDescr.get("typeName", "str")
        #isIdentifier = attrDescr.get("isIdentifier", False)
        #pr "<p>%s: %s (%s)</p>" % (name, typeName, isIdentifier)
        D = {}
        D["name"] = name
        D["kind"] = typeName
        D["setname"] = setName
        for (X,defaultX) in (("isIdentifier",False), 
                             ("isMandatory",True), 
                             ("isOnto",False), 
                             ("isOneToOne",False), 
                             ("isMultiple",False)):
            isX = attrDescr.get(X, defaultX)
            if isX:
                D[X+"Checked"] = 'checked="true"'
            else:
                D[X+"Checked"] = ""
        return (ROWTEMPLATE % D, ROWJAVASCRIPTTEMPLATE % D)

ROWTEMPLATE = """
<tr>
<td> <input name="attributeName_%(name)s" id="attributeName_%(name)s" 
            value="%(name)s"> </td>
<td> 
<div>
<input size="20" id="attributeKind_%(name)s" name="attributeKind_%(name)s" value="%(kind)s"> 
</div>
</td>
<th> <input name="attributeIsIdentifier_%(name)s" type="checkbox" %(isIdentifierChecked)s> </th>
<th> <input name="attributeIsMandatory_%(name)s" type="checkbox" %(isMandatoryChecked)s> </th>
<th> <input name="attributeIsOnto_%(name)s" type="checkbox" %(isOntoChecked)s> </th>
<th> <input name="attributeIsOneToOne_%(name)s" type="checkbox" %(isOneToOneChecked)s> </th>
<th> <input name="attributeIsMultiple_%(name)s" type="checkbox" %(isMultipleChecked)s> </th>
<th> <a href="#" onclick="deleteAttribute('%(setname)s', '%(name)s')">X</a> </th>
</tr>
"""

ROWJAVASCRIPTTEMPLATE = """
$(function() { 
var inputElt = document.getElementById("attributeKind_%(name)s");
//al("found attributeKind_%(name)s "+inputElt);
$(inputElt).autocomplete({
source: availableKinds
});    
});
"""

JSTEMPLATE = """
var availableKinds = %(availableKinds)s;
"""

TEMPLATE = """

<form>
<p>%(nameDisplay)s<p>

<input name="descriptionSetNameBefore" type="hidden" value="%(name)s">
<p> name: <input name="descriptionSetNameAfter" id="descriptionSetNameAfter" 
                 value="%(name)s">  </p>
<table>
<tr> <th> attribute </th> <th> kind </th> 
<th>+key </th> 
<th>required </th> 
<th>onto </th> 
<th>1-1 </th> 
<th>multiple </th> 
</tr>
%(body)s
</table>

</form>

"""

__middleware__ = clickCallBack
